package com.cookapp.service;

import com.cookapp.common.exception.BusinessException;
import com.cookapp.common.enums.ResultCode;
import com.cookapp.common.utils.JwtUtils;
import com.cookapp.model.dto.LoginDTO;
import com.cookapp.model.entity.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * 微信登录服务
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class WxLoginService {

    private final WxMaService wxMaService;
    private final UserService userService;

    /**
     * 微信小程序登录
     */
    public String login(LoginDTO loginDTO) {
        try {
            // 获取微信用户信息
            WxMaJscode2SessionResult session = wxMaService.jsCode2SessionInfo(loginDTO.getCode());
            String openId = session.getOpenid();
            
            // 获取用户信息
            User user = userService.getByOpenId(openId);
            if (user == null) {
                // 新用户，创建用户信息
                user = createUser(openId, loginDTO);
            } else {
                // 更新用户信息
                updateUserInfo(user, loginDTO);
            }
            
            // 生成JWT token
            return JwtUtils.generateToken(user.getId());
        } catch (WxErrorException e) {
            log.error("微信登录失败", e);
            throw new BusinessException(ResultCode.WECHAT_LOGIN_ERROR);
        }
    }

    /**
     * 创建新用户
     */
    private User createUser(String openId, LoginDTO loginDTO) {
        User user = new User();
        user.setOpenId(openId);
        user.setNickname(loginDTO.getNickname());
        user.setAvatar(loginDTO.getAvatar());
        user.setGender(loginDTO.getGender());
        user.setStatus(1);
        user.setLastLoginTime(LocalDateTime.now());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        user.setDeleted(0);
        
        userService.createUser(user);
        return user;
    }

    /**
     * 更新用户信息
     */
    private void updateUserInfo(User user, LoginDTO loginDTO) {
        user.setNickname(loginDTO.getNickname());
        user.setAvatar(loginDTO.getAvatar());
        user.setGender(loginDTO.getGender());
        user.setLastLoginTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        
        userService.updateUser(user);
    }
} 